package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Config;
import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;


public class DefaultHandler implements Handler {
    @Override
    public void handle(Parameter request, OutputStream response) {
        // TODO: [222024321072055/苏雨征]
        // 1. 获取请求路径（可能需要将 / 映射到 index.html）
        Config config = Config.getInstance();
        String requestUrl = request.getUrl();
        String targetPath = requestUrl.equals("/") ?
                "index.html" : requestUrl.substring(1);
        Path webRootPath = Paths.get(config.getWebRoot()).toAbsolutePath().normalize();
        Path filePath = webRootPath.resolve(targetPath).toAbsolutePath().normalize();
        // 安全校验：确保请求的文件在 webroot 目录内（防止路径穿越）
        if (!filePath.startsWith(webRootPath)) {
            send403Forbidden(response, "Access denied: Invalid path");
            return;
        }
        try {
            if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
                byte[] fileBytes = Files.readAllBytes(filePath);

                // TODO: [222024321072055/苏雨征] 确定并设置正确的 Content-Type (例如 text/html, image/jpeg 等)
                String contentType = Files.probeContentType(filePath);
                // 若无法探测类型（如自定义后缀），默认使用二进制流类型
                if (contentType == null) {
                    contentType = "application/octet-stream";
                }

                // 写入 200 OK 响应头
                response.write(("HTTP/1.1 200 OK\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("Content-Type: " + contentType + "\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("Content-Length: " + fileBytes.length + "\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("Connection；close\r\n").getBytes(StandardCharsets.UTF_8));
                response.write(("\r\n").getBytes(StandardCharsets.UTF_8));

                // 写入文件内容
                response.write(fileBytes);
            } else {
                // 文件不存在，返回 404 Not Found
                String content = "<!DOCTYPE html>\r\n" +
                        "<html><head><meta charset='UTF-8'><title>404 Not Found</title></head>\r\n" +
                        "<body><h1 style='color:red'>404 Not Found</h1>\r\n" +
                        "<p>The requested resource <strong>" + requestUrl + "</strong> was not found.</p></body></html>";
                sendResponse(response, 404, "Not Found", "text/html; charset=UTF-8", content);
            }
        } catch (IOException e) {
            // TODO: [222024321072055/苏雨征] 文件读取异常，返回 500 Internal Server Error
            System.err.println("File read error: " + e.getMessage());
            String errorMsg = "<!DOCTYPE html>\r\n" +
                    "<html><head><meta charset='UTF-8'><title>500 Error</title></head>\r\n" +
                    "<body><h1 style='color:red'>500 Internal Server Error</h1>\r\n" +
                    "<p>Failed to read resource: " + e.getMessage() + "</p></body></html>";
            sendResponse(response, 500, "Internal Server Error", "text/html; charset=UTF-8", errorMsg);
        } finally {
            try {
                response.flush();
            } catch (IOException e) {
                System.err.println("Response flush error："+e.getMessage());
            }
        }
    }
    //发送403禁止访问响应
    private void send403Forbidden(OutputStream response, String msg) {
        String content = "<!DOCTYPE html>\r\n" +
                "<html><head><meta charset='UTF-8'><title>403 Forbidden</title></head>\r\n" +
                "<body><h1 style='color:red'>403 Forbidden</h1>\r\n" +
                "<p>" + msg + "</p></body></html>";
        sendResponse(response, 403, "Forbidden", "text/html; charset=UTF-8", content);
    }
    //发送指定状态码和内容的HTTP响应
    private void sendResponse(OutputStream response, int statusCode, String statusDesc,
                              String contentType, String content) {
        try {
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            // 构建响应头
            String responseHeader = "HTTP/1.1 " + statusCode + " " + statusDesc + "\r\n" +
                    "Content-Type: " + contentType + "\r\n" +
                    "Content-Length: " + contentBytes.length + "\r\n" +
                    "Connection: close\r\n" +
                    "\r\n";
            // 发送响应头和响应体
            response.write(responseHeader.getBytes(StandardCharsets.UTF_8));
            response.write(contentBytes);
        } catch (IOException e) {
            System.err.println("Send response error: " + e.getMessage());
        }
    }
}
